package com.chen.usersys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.chen.usersys.domain.ResponseCommon;
import com.chen.usersys.domain.User;
import com.chen.usersys.mapper.UserMapper;
import com.chen.usersys.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional(readOnly = true)
    @Override
    public ResponseCommon login(String name, String pwd, HttpServletRequest request) {
        // 校验账号密码
        if (StrUtil.isAllBlank(name, pwd)) {
            return new ResponseCommon("账号或密码不能为空");
        }
        // 查询用户
        User user = userMapper.selectUserByName(name);
        if (ObjectUtil.isEmpty(user)) {
            return new ResponseCommon("未查到用户");
        }
        // 校验密码
        if (!user.getUPwd().equals(pwd)) {
            return new ResponseCommon("密码错误");
        }
        return new ResponseCommon(user.getUCode(), user.getUType(), "登录成功");
    }

    @Override
    public Integer deleteUserById(Integer id) {
        return userMapper.deleteUserById(id);
    }

    @Transactional(readOnly = true)
    @Override
    public List<User> selectAllUser() {
        return userMapper.selectUserList();
    }

    @Override
    public String insertUser(User user) {
        try {
            if (user == null) {
                return "用户为空";
            }
            // 创建一个 User 对象并设置其属性
            User newUser = new User();
            BeanUtils.copyProperties(user, newUser);
            if (user.getUType() == null) {
                newUser.setUType(1);
            }
            // 保存用户数据
            userMapper.insertUser(user);
            // 返回成功消息
            return "用户保存成功";
        } catch (Exception e) {
            e.printStackTrace();
            // 如果保存失败，则返回错误消息
            return "保存用户失败：" + e.getMessage();
        }
    }

    @Override
    public Integer updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Transactional(readOnly = true)
    @Override
    public User selectById(Integer id) {
        return userMapper.selectUserById(id);
    }
}
